/*******************************************************************************
 * Package: com.song.batch
 * Type:    CsvBeanValidator
 * Date:    2024-01-19 22:09
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.batch;

import org.springframework.batch.item.validator.Validator;
import org.springframework.beans.factory.InitializingBean;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 功能描述：
 *  开启对Validator依赖包提供校验注解支持，来校验ItemReader读取到的数据是否满足要求。
 * 我们可以让我们的ItemProcessor实现ValidatingItemProcessor接口
 * @author Songxianyang
 * @date 2024-01-19 22:09
 */
public class CsvBeanValidator<T> implements Validator<T>, InitializingBean {

    private javax.validation.Validator validator;

    // 使用JSR-303的Validator来校验我们的数据，在此处进行JSR-303的Validator的初始化。
    @Override
    public void afterPropertiesSet() {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.usingContext().getValidator();
    }

    // 使用Validator的validate方法校验数据。
    @Override
    public void validate(T value) throws ValidationException {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(value);
        if (constraintViolations.size() > 0) {
            StringBuilder message = new StringBuilder();
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                message.append(constraintViolation.getMessage())
                        .append("\n");
            }
            throw new ValidationException(message.toString());
        }
    }
}
